package com.pengpeng.flash.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pengpeng.flash.common.CustomException;
import com.pengpeng.flash.entity.Category;
import com.pengpeng.flash.entity.Dish;
import com.pengpeng.flash.entity.Setmeal;
import com.pengpeng.flash.mapper.CategoryMapper;
import com.pengpeng.flash.service.CategoryService;
import com.pengpeng.flash.service.DishService;
import com.pengpeng.flash.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    DishService dishService;

    @Autowired
    SetmealService setmealService;

    /**
     * 根据id删除分类，但在删除之前要先查看此分类有没有绑定菜品
     * @param id
     */
    @Override
    public void remove(Long id) {
        //检查当前分类是否关联菜品，若关联，抛出异常
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        //查询当前分类中的菜品数量
        int count = dishService.count(dishLambdaQueryWrapper);
        if (count > 0){
            //已经关联菜品，抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品，不能删除...");
        }


        //检查当前分类是否关联套餐，若关联，抛出异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        //查询当前分类中的套餐数量
        int count1 = setmealService.count(setmealLambdaQueryWrapper);
        if (count1 > 0){
            //已经关联菜品，抛出一个业务异常
            throw new CustomException("当前分类下关联了套餐，不能删除...");
        }

        //正常删除
        super.removeById(id);
    }
}
